/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

package com.huawei.saashousekeeper.dbpool.creator;

import com.huawei.saashousekeeper.constants.DbPoolEnum;
import com.huawei.saashousekeeper.dbpool.druid.DruidPool;
import com.huawei.saashousekeeper.properties.DataSourceProperty;

import com.alibaba.druid.pool.DruidDataSource;

import lombok.extern.slf4j.Slf4j;

import java.sql.SQLException;
import java.util.Optional;

import javax.sql.DataSource;

/**
 * druid数据源创建器
 *
 * @author lWX1156935
 * @since 2022/4/22
 */
@Slf4j
public class DruidDataSourceCreator implements DataSourceCreator {
    /**
     * 获取池名称
     *
     * @return 池名称
     */
    @Override
    public String getPoolName() {
        return DbPoolEnum.POOL_DRUID.getName();
    }

    @Override
    public DataSource createDataSource(DataSourceProperty dataSourceProperty) {
        DruidPool poolTemplate = (DruidPool) dataSourceProperty.getPool(getPoolName());
        DruidDataSource dataSource = poolTemplate != null ? poolTemplate : new DruidPool();
        dataSource.setUsername(dataSourceProperty.getUsername());
        dataSource.setPassword(dataSourceProperty.getPassword());
        dataSource.setUrl(dataSourceProperty.getUrl());
        Optional.ofNullable(dataSourceProperty.getDriverClassName()).ifPresent(dataSource::setDriverClassName);
        try {
            dataSource.init();
        } catch (SQLException e) {
            log.error("druid pool init failed {}", dataSource.getName());
        }
        return dataSource;
    }

    /**
     * 关闭连接池
     *
     * @param dataSource 数据源
     * @return 关闭结果
     */
    @Override
    public boolean close(DataSource dataSource) {
        if (dataSource == null) {
            return true;
        }
        if (dataSource instanceof DruidDataSource) {
            ((DruidDataSource) dataSource).close();
            return true;
        }
        return false;
    }
}
